package com.bosssoft.hr.train.j2se.collection;

import com.bosssoft.hr.train.j2se.pojo.entity.User;

import java.util.*;

/**
 * ThreadArrayListDemo
 */
public class ThreadArrayListDemo {
    private ArrayList<String> arrayList = new ArrayList<>();

    /**
     * 测试生产者和消费者进行数据操作
     * @throws Exception
     */
    public void test() throws Exception{
        Thread t1 = new Thread(new producerThread(arrayList));
        Thread t2 = new Thread(new consumerThread(arrayList));
        t1.setName("生产者");
        t2.setName("消费者");
        t1.start();
        t2.start();
    }

    /**
     * 生产者线程
     */
    public class producerThread implements Runnable{
        ArrayList<String> arrayList;

        public producerThread(ArrayList<String> arrayList) {
            this.arrayList = arrayList;
        }

        @Override
        public void run() {
            while(true){
                synchronized (arrayList){
                    if (arrayList.size()>0){
                        try{
                            arrayList.wait();
                        }catch (InterruptedException e){
                            e.printStackTrace();
                        }
                    }
                    Random random = new Random();
                    String str = "用户"+ random.nextInt(10);
                    arrayList.add(str);
                    System.out.println(Thread.currentThread().getName()+"生产了："+str);
                    arrayList.notify();
                }
            }

        }
    }

    /**
     * 消费者线程
     */
    public class consumerThread implements Runnable{
        ArrayList<String> arrayList;

        public consumerThread(ArrayList<String> arrayList) {
            this.arrayList = arrayList;
        }

        @Override
        public void run() {
            while(true){
                synchronized (arrayList){
                    if (arrayList.size() == 0){
                        try {
                            arrayList.wait();
                        }catch (InterruptedException e){
                            e.printStackTrace();
                        }
                    }
                    String str = arrayList.remove(0);
                    System.out.println(Thread.currentThread().getName()+"消费了："+str);
                    arrayList.notify();
                }
            }

        }
    }
}
